package com.woke.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.woke.HtmlActivity;
import com.example.woke.LoadActivity;
import com.example.woke.MoneyonlineActivity;
import com.example.woke.ReciverFActivity;
import com.example.woke1.CaixintongActivity;
import com.example.woke1.ZhcailicaiActivity;
import com.example.woke1.ZhongchouActivity;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.woke.addressactivity.ExChangeActivity;
import com.woke.method.MyApp;
import com.woke.method.MyViewPager;
import com.zbar.woke.CaptureActivity;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class HomepageFragment extends Fragment implements OnPageChangeListener, OnClickListener {

    private View layout;
    private LayoutInflater minflater;
    private MyViewPager mPager;
    //	private GridView mGridView;
    private ArrayList<View> mLayouts;
    private boolean userScroll;
    //	private ImageLoader imageLoader;
    private ArrayList<String> list = new ArrayList<String>();//���ͼ
    private ArrayList<String> list1 = new ArrayList<String>();//�������
    private ArrayList<String> ninelist = new ArrayList<String>();
    private ArrayList<String> namelist = new ArrayList<String>();//��������
    private AlertDialog alertDialog;
    private Intent intent = new Intent();
    private int higdkl = 0;
    private RelativeLayout mRelativeLayout;
    private MyApp application;
    private TextView mErweima;
    private int currcunt = 0;//��ǰҳ
    private ImageView imageView;
    private LinearLayout mIndicatorLayout;
    private static int screenWidth;
    private static int screenHeigh;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (layout == null) {
            minflater = inflater;
//			imageLoader = new ImageLoader (getActivity ());
            layout = minflater.inflate(R.layout.frment_homepage1, null);
//			DisplayMetrics dm = new DisplayMetrics();
            application = (MyApp) getActivity().getApplication();
            intview();
        } else {
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeView(layout);
            }
        }
        return layout;
    }

    @Override
    public void onDestroy() {
//		imageLoader.clearCache ();
//		imageLoader.clearMemoryCache ();
        super.onDestroy();
    }

    private void intview() {
        DisplayMetrics dm = new DisplayMetrics();
        application = (MyApp) getActivity().getApplication();
        //��ȡ��Ļ��Ϣ
//		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//		screenWidth = dm.widthPixels;
//		screenHeigh = dm.heightPixels;
//		application.screenWidth =screenWidth;
        ninelist.add("中财支付");
        ninelist.add("中财借贷");
        ninelist.add("中财理财");
        ninelist.add("中财众筹");
        ninelist.add("财信通");
        ninelist.add("中交所");
        mRelativeLayout = (RelativeLayout) layout.findViewById(R.id.fmhome_relite_yout);
        LayoutParams layoutParams2 = mRelativeLayout.getLayoutParams();
        int height = layoutParams2.height;
        mPager = (MyViewPager) layout.findViewById(R.id.frment_viewager);
        layout.findViewById(R.id.fm_home_n1).setOnClickListener(this);
        layout.findViewById(R.id.fm_home_n2).setOnClickListener(this);
        layout.findViewById(R.id.fm_home_n3).setOnClickListener(this);
        layout.findViewById(R.id.fm_home_n4).setOnClickListener(this);
        layout.findViewById(R.id.fm_home_n5).setOnClickListener(this);
        layout.findViewById(R.id.fm_home_n6).setOnClickListener(this);
        mErweima = (TextView) layout.findViewById(R.id.fmhome_image_erweima);
        mErweima.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivity(intent);
            }
        });

        getpersondata();//��ȡ���ͼƬ��ַ
    }


    private void getpersondata() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "Ads");
        params.put("a", "adsList");
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("r上", "" + response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        JSONObject jsonObject = response.getJSONObject("data");
                        JSONArray arra = jsonObject.getJSONArray("data");
                        for (int i = 0; i < arra.length(); i++) {
                            JSONObject data = arra.getJSONObject(i);
                            String ad_content = data.getString("ad_content");
                            String ad_pic = data.getString("ad_pic");
                            String ad_url = data.getString("ad_url");
                            String status = data.getString("status");
                            String ad_name = data.getString("ad_name");
                            String ad_id = data.getString("ad_id");
                            list.add("http://" + ad_pic);
                            list1.add(ad_url);
                            namelist.add(ad_name);
                            if (i == 1) {
                                String strBase64 = new String(Base64.encode("1".getBytes(), Base64.DEFAULT));
                                String shareurl = ad_url + "/NOxBL7xp/" + strBase64;
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (list.size() > 0) {
                    loadtopimage();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(getActivity(), "信息获取失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
//				mBar.setVisibility(View.GONE);
                Log.e("response", "完成");
            }
        });
    }

    private void loadtopimage() {
        mLayouts = new ArrayList<View>();
        if (minflater == null) {
            minflater = LayoutInflater.from(getActivity());
        }
        mIndicatorLayout = (LinearLayout) layout.findViewById(R.id.indicator);
        for (int i = 0; i < list.size(); i++) {
            // ��̬���ָʾ��ImageView����
            View indicatorView = minflater.inflate(
                    R.layout.indicator, null);
            // ImageView indicator = new ImageView(this);
            mIndicatorLayout.addView(indicatorView);
            // ����PagerItem����
            View layout = minflater.inflate(R.layout.pager_item, null);
            imageView = (ImageView) layout
                    .findViewById(R.id.image_guanggao);
//            imageView.setImageResource(mDrawables[i]);
            mLayouts.add(layout);
        }
        mPager.setAdapter(new MyAdapter());
        mPager.setOnPageChangeListener(this);
        mPager.setCurrentItem(4000);
        mPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        userScroll = true;
                        break;
                    case MotionEvent.ACTION_UP:

                        userScroll = false;
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        mPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!userScroll) {
                    mPager.setCurrentItem(mPager
                            .getCurrentItem() + 1);
                }
                mPager.postDelayed(this, 4000);
            }
        }, 4000);
    }

    public class MyAdapter extends PagerAdapter {
        @Override
        public Object instantiateItem(View container, int position) {
            View layout = minflater.inflate(R.layout.pager_item, null);
            ImageView mGmage = (ImageView) layout.findViewById(R.id.image_guanggao);
            mGmage.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
//					http://app
                    Intent intent = new Intent(getActivity(), HtmlActivity.class);
                    intent.putExtra("urlname", namelist.get(mPager.getCurrentItem() % namelist.size()));
                    Log.e("url", namelist.get(mPager.getCurrentItem() % namelist.size()));
                    if (null == application.getDatas_load()) {
                        if (list1.get(mPager.getCurrentItem() % namelist.size())
                                .substring(0, 10)
                                .equals("http://app")) {
                            String strBase64 = new String(Base64.encode("1".getBytes(), Base64.DEFAULT));
                            intent.putExtra("url", list1.get(mPager.getCurrentItem() % namelist.size()) + "/NOxBL7xp/" + strBase64);
                        } else {
                            intent.putExtra("url", list1.get(mPager.getCurrentItem() % namelist.size()));
                        }
                    } else {
                        if (list1.get(mPager.getCurrentItem() % namelist.size())
                                .substring(0, 10)
                                .equals("http://app")) {
                            String strBase64 = new String(Base64.encode(application.getDatas_load()
                                    .getId()
                                    .getBytes(), Base64.DEFAULT));
                            intent.putExtra("url", list1.get(mPager.getCurrentItem() % namelist.size()) + "/NOxBL7xp/" + strBase64);
                        } else {
                            intent.putExtra("url", list1.get(mPager.getCurrentItem() % namelist.size()));
                        }
                    }
                    startActivity(intent);
                }
            });
            if (list.size() > 0) {
                GlideApp.with(container.getContext())
                        .load(list.get(position % list.size()))
                        .placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)
                        .into(mGmage);
//        		imageLoader.DisplayImage(list.get(position % list.size()), mGmage, false, false, true,0);

            }
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeView(layout);
            }
            mPager.addView(layout);
            currcunt = position;
            return layout;
        }

        @Override
        public void destroyItem(View container,
                                int position, Object object) {
            View layout = mLayouts.get(position % list.size());
            mPager.removeView(layout);
        }

        @Override
        public int getCount() {
            return 8000;
        }

        @Override
        public boolean isViewFromObject(View view,
                                        Object obj) {
            return view == obj;
        }
    }


    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int arg0) {
        for (int i = 0; i < list.size(); i++) {
            View layout = mIndicatorLayout.getChildAt(i);
            ImageView img = (ImageView) layout
                    .findViewById(R.id.img);
            if (i == (arg0 % list.size())) {
                img.setImageResource(R.drawable.indicator_selected);
            } else {
                img.setImageResource(R.drawable.indicator_normal);
            }
        }

    }


    private void aralogid(String info, String kll, final int ppp) {
        alertDialog = new AlertDialog.Builder(getActivity()).
                setTitle(info).
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        intent.setClass(getActivity(), LoadActivity.class);
                        startActivity(intent);
                        alertDialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        }).create();
        alertDialog.show();
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.fm_home_n1:
                if (application.getDatas_load() == null) {
                    aralogid("还未登录", "前往登录", 1);
                } else {
                    intent.setClass(getActivity(), ReciverFActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.fm_home_n2:
                intent.setClass(getActivity(), MoneyonlineActivity.class);
                startActivity(intent);
                break;

            case R.id.fm_home_n3:
                if (application.getDatas_load() == null) {
                    aralogid("还未登录", "前往登录", 1);
                } else {
                    intent.setClass(getActivity(), ZhcailicaiActivity.class);
                    startActivity(intent);
                }
//			Toast.makeText(getActivity(), "������δ��ͨ", Toast.LENGTH_SHORT).show();
                break;

            case R.id.fm_home_n4:
                if (application.getDatas_load() == null) {
                    aralogid("还未登录", "前往登录", 1);
                } else {
                    intent.setClass(getActivity(), ZhongchouActivity.class);
                    startActivity(intent);
                }
//			Toast.makeText(getActivity(), "������δ��ͨ", Toast.LENGTH_SHORT).show();
                break;

            case R.id.fm_home_n5:
                if (application.getDatas_load() == null) {
                    aralogid("还未登录", "前往登录", 1);
                } else {
                    intent.setClass(getActivity(), CaixintongActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.fm_home_n6:
//                intent.setClass(getActivity(), ZhongjinsuoActivity.class);
                intent.setClass(getActivity(), ExChangeActivity.class);
                startActivity(intent);
//			Toast.makeText(getActivity(), "������δ��ͨ", Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
        }
    }
}
